<?php
namespace Core;
use \GatewayWorker\Lib\Db;
use \GatewayWorker\Lib\Gateway;
//系统消息
class SystemMessage{
    public static function system_users(){
        $sql=<<<EFO
SELECT * FROM `b_shop_message_sysuser` as s
EFO;
        $db1 = Db::instance('db')->query($sql);
        foreach($db1 as $key=>$value){
            $db1[$key]['count'] = 0;
        }
        $result['items'] = $db1;
        $result['noread_count'] = $db1 ? array_sum(array_column($db1,'count')) : 0;
        return self::json_return('system_users',$result,'获取系统用户成功');
    }

    public static function message_list($data){
        $sql=<<<EFO
select ms.id,ms.shop_id,ms.sys_id,ms.created_at,ms.message as content,ms.type,ms.extends,ms.msg_type,msuser.nickname,msuser.avatar from `b_shop_message_sysmess` as ms
left join b_shop_message_sysuser as msuser on ms.sys_id=msuser.sys_id
where (ms.shop_id=0 or ms.shop_id = {$data['shop_id']}) AND ms.sys_id="{$data['sys_id']}"
ORDER BY ms.created_at asc
EFO;
        $db1 = Db::instance('db')->query($sql);
        foreach ($db1 as $key=>$value){
            $db1[$key]['created_at'] = self::format_date($value['created_at']);
        }
        return self::json_return('system_message_list',$db1,'获取系统用户成功');

    }



    /**
     * 数据返回
     */
    public static function json_return($type,$data,$msg){
        $result['type'] = $type;
        $result['data']=$data;
        $result['msg']=$msg;
        return json_encode($result);
    }

    /**
     * 计算两个时间之差
     * @param $time
     * @return string
     */
    public static function format_date($date){
        $time = strtotime($date);
        $t=time()-$time;
        $f=array(
            '31536000'=>'年',
            '2592000'=>'个月',
            '604800'=>'星期',
            '86400'=>'天',
            '3600'=>'小时',
            '60'=>'分钟',
            '1'=>'秒'
        );
        foreach ($f as $k=>$v)    {
            if (0 !=$c=floor($t/(int)$k)) {
                return $c.$v.'前';
            }
        }
    }
}